package cn.itcast.bos.action;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.utils.BaseAction;
import cn.itcast.bos.utils.SmsUtils;

import com.itheima.crm.domain.Customer;

@ParentPackage("json-default")
@Namespace("/")
@Scope("prototype")
@Controller
public class CustomerAction extends BaseAction<Customer> {

	@Action(value = "customer_sendSms")
	public String sendSms() throws IOException {
		// 手机号码保存在Customer对象中
		// 生成4位随机数
		String randomCode = RandomStringUtils.randomNumeric(4);
		// 将短信验证码保存到session中
		ServletActionContext.getRequest().getSession()
				.setAttribute(model.getTelephone(), randomCode);
		System.out.println("生成的手机验证码为：" + randomCode);
		// 编辑短信内容
		String msg = "尊敬的用户你好，你本次的验证码为：" + randomCode + ",服务电话4006184000";
		// 调用sms服务器发送短信
		// String result = SmsUtils.sendSmsByHTTP(model.getTelephone(), msg);
		String result = "000/xxxx";
		if (result.startsWith("000")) {
			// 发送成功
			return NONE;
		} else {
			// 发送失败
			throw new RuntimeException("短信发送失败，请与管理员联系" + result);
		}

	}

	// 属性注入
	private String checkcode;

	public void setCheckcode(String checkcode) {
		this.checkcode = checkcode;
	}

	@Action(value = "customer_regist", results = {
			@Result(name = "success", type = "redirect", location = "signup-success.html"),
			@Result(name = "input", type = "redirect", location = "signup.html") })
	public String regist() {
		// 先校验短信验证码，如果不正确则跳回注册界面
		// 从session中获取验证码
		String sessionCode = (String) ServletActionContext.getRequest()
				.getSession().getAttribute(model.getTelephone());
		// 判断验证码是否一致
		if (sessionCode == null || !sessionCode.equals(checkcode)) {
			// 验证码不一致
			System.out.println("验证码不正确。。。。");
			return INPUT;
		}
		// 调用webservice 连接crm 保存客户信息
		WebClient
				.create("http://localhost:8083/service/"
							+"customerService/customer")
				.type(MediaType.APPLICATION_JSON).post(model);
		//发送一封邮箱绑定的邮件
		
		System.out.println("注册成功！");
		return SUCCESS;
	}
}
